<template>
  <div class="wrapper">
    <el-header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>智能问诊</p>
      <div></div>
    </el-header>
    <el-main>
      <div class="chat-container">
        <div class="chat-history" ref="chatHistory">
          <div v-for="(message, index) in conversationHistory" :key="index" class="message" :class="message.role">
            <div class="message-content">
              <img v-if="message.role === 'assistant'" :src="getAvatar('assistant')" class="avatar" />
              <p>{{ message.content }}</p>
              <img v-if="message.role === 'user'" :src="getAvatar('user')" class="avatar user-avatar" />
            </div>
          </div>
        </div>
        <div class="input-area">
          <el-input v-model="userQuestion" placeholder="请输入你的问题" @keyup.enter="sendQuestionToOpenAI" />
          <el-button @click="sendQuestionToOpenAI">发送</el-button>
        </div>
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElHeader, ElMain, ElInput, ElButton } from 'element-plus';
import axios from 'axios';

const userQuestion = ref('');
const openAIResponse = ref(null);
const conversationHistory = ref([]); // 新增对话历史数组
const chatHistory = ref(null);

const goBack = () => {
  history.go(-1);
};

const sendQuestionToOpenAI = async () => {
  try {
    const apiKey = 'sk-1la5p6o60h5urbnaco7jqrrm46vot6r11u6a1vbsqm60abv2';
    const question = userQuestion.value;
    conversationHistory.value.push({ role: "user", content: question });
    userQuestion.value = ''; // 清空输入框
    const response = await axios.post(
      'https://api.aihao123.cn/luomacode-api/open-api/v1/chat/completions',
      {
        model: "gpt-3.5-turbo",
        messages: conversationHistory.value // 传递对话历史
      },
      {
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        }
      }
    );
    const answer = response.data.choices[0].message.content;
    conversationHistory.value.push({ role: "assistant", content: answer });
    openAIResponse.value = answer;
    chatHistory.value.scrollTop = chatHistory.value.scrollHeight;
  } catch (error) {
    console.error(error);
    openAIResponse.value = '很抱歉，请求出现错误，请稍后再试。';
  }
};

// 获取头像
const getAvatar = (role) => {
  if (role === 'user') {
    return new URL('@/assets/images/user-avatar.png', import.meta.url).href;
  } else {
    return new URL('@/assets/images/ai-avatar.png', import.meta.url).href;
  }
};

// 在组件加载时发送欢迎消息
onMounted(async () => {
  try {
    const welcomeMessage = '欢迎使用智能问诊！请问有什么我可以帮助您的？';
    conversationHistory.value.push({ role: "assistant", content: welcomeMessage });
    chatHistory.value.scrollTop = chatHistory.value.scrollHeight;
  } catch (error) {
    console.error(error);
  }
});
</script>

<style scoped>
/*********************** 总容器 ***********************/
.wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/*********************** header ***********************/
.el-header {
  width: 100%;
  height: 15.7vw;
  background-color: #FFF;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 3.6vw;
  z-index: 10;
}
.el-header .fa {
  font-size: 8vw;
}

/*********************** 聊天容器 ***********************/
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  /* padding: 0 3.6vw; */
  padding-bottom: 60px; 
}

/*********************** 聊天历史 ***********************/
.chat-history {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10vw;
}

/*********************** 聊天消息 ***********************/
.message {
  display: flex;
  align-items: center;
  margin: 2vw 0;
}
 
.message-content {
  display: flex;
  align-items: center;
}
 
.message p {
  max-width: 54vw; /* 限制消息框宽度 */
  padding: 2vw;
  font-size: 4vw;
  word-wrap: break-word; /* 允许长单词或URL地址换行 */
  border-radius: 12px; /* 设置圆角 */
  position: relative; /* 为三角形设置相对定位 */
}
 
/* AI消息（默认在左边，无需特别调整位置） */
.message.assistant p {
  background-color: #F0F0F0;
  color: #333;
}
 
/* 用户消息框和用户头像 */
.message.user {
  justify-content: flex-end; /* 使内容靠右对齐 */

}
 
.message.user p {
  margin-left: 0; /* 移除之前的自动边距，因为现在是靠右对齐 */
  background-color: #137E92;
  color: #FFF;
}
 
/* 头像样式 */
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px; /* AI头像与消息框的间距 */
}
 
.user-avatar {
  margin-left: 10px; /* 用户头像与消息框的间距，但现在它在右边，所以这是左侧间距 */
}

/*********************** 输入区域 ***********************/
.input-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 2vw;
  box-sizing: border-box;
  background-color: #FFF;
  z-index: 10;
}
.input-area .el-input {
  flex: 1;
  margin-right: 2vw;
}
.input-area .el-button {
  width: 12vw;
  height: 12vw;
  background-color: #137E92;
  color: #FFF;
  border: none;
  border-radius: 6vw;
  font-size: 4vw;
}
</style>